package com.hunan.api.catv.interceptor;

import com.google.gson.GsonBuilder;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@EnableWebMvc
@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    /**
     * 默认日期时间格式
     */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /**
     * 默认日期格式
     */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /**
     * 默认时间格式
     */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    private static final Logger LOGGER = LoggerFactory.getLogger(WebAppConfig.class);


    /**
     * gson序列化localdatetime
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
        gsonHttpMessageConverter.setGson(new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .serializeNulls()
                .registerTypeAdapter(LocalDate.class, new GsonUtils.LocalDateAdapter())
                .registerTypeAdapter(LocalTime.class, new GsonUtils.LocalTimeAdapter())
                .registerTypeAdapter(LocalDateTime.class, new GsonUtils.LocalDateTimeAdapter()).create());
        converters.add(gsonHttpMessageConverter);
    }


    @Bean
    public BaseInterceptor getBaseInterceptor() {
        return new BaseInterceptor();
    }


    @Bean
    public SignInterceptor getSignInterceptor() {
        return new SignInterceptor();
    }

    @Bean
    public MonitorMethodInterceptor getMonitorMethodInterceptor() {
        return new MonitorMethodInterceptor();
    }

    @Autowired
    private SystemDictBiz systemDictBiz;

    /**
     * 拦截器链
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String excludeInterfaceListString = systemDictBiz.getStringByKey("excludeInterfaceList");
        LOGGER.info("接口签名例外配置：" + excludeInterfaceListString);
        List<String> excludeInterfaceList = new ArrayList<>();
        if (!StringUtils.isEmpty(excludeInterfaceListString)) {
            excludeInterfaceList = Arrays.asList(excludeInterfaceListString.split(","));
        }

        registry.addInterceptor(getBaseInterceptor())
                .addPathPatterns("/**").excludePathPatterns(excludeInterfaceList);
        registry.addInterceptor(getSignInterceptor())
                .addPathPatterns("/**").excludePathPatterns(excludeInterfaceList);
        registry.addInterceptor(getMonitorMethodInterceptor())
                .addPathPatterns("/**");

    }

    /**
     * LocalDate转换器，用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
    }

    /**
     * LocalDateTime转换器，用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return source -> LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
    }

    /**
     * LocalTime转换器，用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, LocalTime> localTimeConverter() {
        return source -> LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
    }

    /**
     * Date转换器，用于转换RequestParam和PathVariable参数
     */
    @Bean
    public Converter<String, Date> dateConverter() {
        return source -> {
            SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
            try {
                return format.parse(source);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        };
    }
}
